package General;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import Data.Tracks;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.zip.ZipOutputStream;

public class FTPHandle extends AsyncTask<String, String, String>
{
	public FTPClient client = null;
	public FileInputStream fis = null;
	private File root;
	private File dir;
	private Compress CompressorZip = null;
	private String [] ArrayFiles;
	private String FTPDirectoryName;
	private List<String> fileList = new ArrayList<String>();
	private File dir1;
	private String FTPDirectoryName2;
	private Context ContextThis;

	public FTPHandle(Context context)
	{
		Calendar calendar = Calendar.getInstance();
		
		ContextThis = context;
		client = new FTPClient();
		fis = null;	
		root = android.os.Environment.getExternalStorageDirectory();
		dir1 = new File (root.getAbsolutePath()+ "/TrackingDataToSend"); //creates directory
		if(!dir1.exists())
            dir1.mkdirs();
		
		TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(context.TELEPHONY_SERVICE);
        String IMEI = new String(); 
        IMEI = telephonyManager.getDeviceId();
		
		FTPDirectoryName = new String();
		//android.telephony.TelephonyManager.getDeviceId().toString(
		dir = new File (root.getAbsolutePath()+ "/TrackingData");
		
		FTPDirectoryName += (root.getAbsolutePath()+"/TrackingDataToSend/")
				+calendar.get(Calendar.YEAR)+"_"
	   			+(int)(calendar.get(Calendar.MONTH)+1)+"_"
	   			+calendar.get(Calendar.DAY_OF_MONTH)+"_"
	   			+calendar.get(Calendar.HOUR_OF_DAY)+"_"
	   			+calendar.get(Calendar.MINUTE)+"_"
	   			+calendar.get(Calendar.SECOND)+IMEI+".zip";
		FTPDirectoryName2 = new String(); 
		FTPDirectoryName2 +=
				+calendar.get(Calendar.YEAR)+"_"
			   			+(int)(calendar.get(Calendar.MONTH)+1)+"_"
			   			+calendar.get(Calendar.DAY_OF_MONTH)+"_"
			   			+calendar.get(Calendar.HOUR_OF_DAY)+"_"
			   			+calendar.get(Calendar.MINUTE)+"_"
			   			+calendar.get(Calendar.SECOND)+IMEI+".zip";
		execute();
	}
	
	protected String doInBackground(String... arg0) {
		Connect();
		return null;
	}
	
	@SuppressWarnings("static-access")
	public int Connect()
	{
		int status = 0;
		
		if(isOnline())
		{
			try {
				
			    client.connect("opencloud.dyndns.org");
			    client.user("TrackingMe");
			    client.pass("passwd");
			    client.setFileType(FTP.BINARY_FILE_TYPE);
			   
			    // Store file to server
			    ListDir(dir);
			    CompressorZip = new Compress(ArrayFiles, FTPDirectoryName);
			    CompressorZip.zip();
			    fis = new FileInputStream(FTPDirectoryName);  		    
			    client.storeFile(FTPDirectoryName2, fis);
			    client.logout();
			
			    status = 1;
			} catch (IOException e) {
			    e.printStackTrace();
			    
			    status = 0;
			} finally {
			    try {
			        if (fis != null) {
			            fis.close();
			        }
			        client.disconnect();
			    } catch (IOException e) {
			        e.printStackTrace();
			    }
			}
			
			if(status == 1)
				Toast.makeText(ContextThis,"Data Sent", 
	                Toast.LENGTH_SHORT).show();
		}		
		else
			Toast.makeText(ContextThis,"You are not connected to the internet", 
	                Toast.LENGTH_SHORT).show();
		
		return status;
	}
	
	void ListDir(File f){
	     File[] files = f.listFiles();
	     fileList.clear();
	     for (File file : files){
	      fileList.add(file.getPath());  
	     }
	      
	     ArrayFiles = new String [fileList.size()];
	     for(int i=0 ; i < fileList.size() ; i++)
	    	 ArrayFiles[i]=fileList.get(i).toString();
	     
	     Log.d("$$$$$$$$$$$$$$$$$$","$$$$$$$$$$$$$$$$$$$$$$$$$ ERROR 3.3");
	 }
	
	
	 public boolean isOnline() { 

	    	WifiManager wifiManager = (WifiManager) ContextThis.getSystemService(ContextThis.WIFI_SERVICE); 
	        
	        try { 
	                ConnectivityManager cm = (ConnectivityManager) ContextThis.getSystemService(ContextThis.CONNECTIVITY_SERVICE); 
	                
	                if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) { 
	                	Log.d("####","Conected to WIFI Internet"); 
	                    Log.d("####","Connection status Wifi: "+cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
	                        return true; 
	                } 
	                else{
		             // turn on wifi
		            	if(!wifiManager.isWifiEnabled()){
		            		wifiManager.setWifiEnabled(true);
		            	}
		            	
		                if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) { 
		                	Log.d("####","Conected to WIFI Internet"); 
		                    Log.d("####","Wifi connection status: "+cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
		                       return true; 
		                } else {
		                	
		           
		                	if(cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()){ 
		                	
		                	 Log.d("####", "Conected to 3G Internet"); 
		                     Log.d("####","3G connection status: " + cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());
		                     	return true; 
		                	} 
		                	else { 
		                		
		                		//turn on 3G
		                		//ConnectivityManager mgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		                		//Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
		                		//dataMtd.setAccessible(true);
		                		//dataMtd.invoke(mgr, true); 
		                		
		                			//test again
		                		if(cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()){ 
		                        	
		                		Log.d("####", "Conected to 3G Internet"); 
		   	                    Log.d("####","3G connection status: " + cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());
		   	                     	return true; 
		                       	} 
		                		else
		                		{
		                			Log.e("####","Wifi connection status: "+cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()); 
		                            Log.e("####","Wifi connection status: : "+cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()); 
		                            return false; 
		                		}
		                	} 
		                }
	              }
	        } 

	        catch (Exception e) { 
	                Log.e("####", "Error on connecting to the Internet: " + e.getMessage()); 
	                return false; 
	        } 
	    } 
	
}
